/**   
 *    
 * 项目名称：SmartKungFu   
 * 类名称：MstUserController   
 * 类描述：   系统用户控制层
 * 创建人：zhangl  
 * 创建时间：2016年9月24日 下午5:04:54   
 * 修改人：zhangl   
 * 修改时间：2016年9月24日 下午5:04:54   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.controller;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.github.miemiedev.mybatis.paginator.domain.Paginator;
import com.lst.common.BaseController;
import com.lst.common.CommonEnum;
import com.lst.exception.MyException;
import com.lst.model.FolPara;
import com.lst.model.MstButton;
import com.lst.model.MstUser;
import com.lst.model.MySession;
import com.lst.model.Resources;
import com.lst.model.UserRole;
import com.lst.service.MstButtonService;
import com.lst.service.MstUserService;
import com.lst.service.ResourcesService;
import com.lst.service.UserRoleService;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;

/**
 * @ClassName: MstUserController
 * @Description: 系统用户控制层
 * @author zhangl
 * @date 2016年9月24日 下午5:04:54
 *
 */
@Controller
@RequestMapping("/mstUserController/*")
public class MstUserController extends BaseController{

	@Autowired
	private MstUserService mstUserService;

	@Autowired
	private UserRoleService userRoleService;

	@Autowired
	private MstButtonService mstButtonService;

	@Autowired
	private ResourcesService resourcesService;

	/**
	 * 
	 * @Title: list
	 * @Description:list页面
	 * @param @return    设定文件
	 * @return ModelAndView    返回类型
	 * @throws MyException 
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(
			@RequestParam(required = true) int menuId,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGE)Integer page,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) Integer rows,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che,
			@RequestParam(required = false,defaultValue = "") String minDate,
			@RequestParam(required = false,defaultValue = "") String maxDate,
			@RequestParam(required = false,defaultValue = "") String usrAccount,
			@RequestParam(required = false,defaultValue = "") String mobileNo,
			@RequestParam(required = false,defaultValue = "") String nameCn) throws MyException{
		Date startDate = new Date();
		logger.info("list begin: " + startDate);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_SYSTEM + "/user_list");

		//写参数
		FolPara folPara = new FolPara();
		folPara.setPage(page);
		folPara.setRows(rows);
		folPara.setUsrAccount(usrAccount);;
		folPara.setMinDate(minDate);
		folPara.setMaxDate(maxDate);
		folPara.setNameCn(nameCn);
		folPara.setMobileNo(mobileNo);
		folPara.setMenuId(menuId);

		MstUser mstUser = this.getMySession().getMstUser();
		List<MstButton> btns = CommonUtils.readPermissionWithBtn(menuId, mstUser, mstButtonService);

		mv.addObject("folPara", folPara);
		mv.addObject("btns", btns);

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("list end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: queryList
	 * @Description: 获取数据集
	 * @param @param page
	 * @param @param rows
	 * @param @param minDate
	 * @param @param maxDate
	 * @param @param account
	 * @param @param mobileNo
	 * @param @param namecn
	 * @param @return    设定文件
	 * @return Object    返回类型
	 */
	@RequestMapping(value = "/queryList")
	@ResponseBody
	public Object queryList(
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGE) Integer page,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) Integer rows,
			@RequestParam(required = false,defaultValue = "")String sort,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEM_ORDER_DESC)String order,
			@RequestParam(required = false,defaultValue = "")String minDate,
			@RequestParam(required = false,defaultValue = "")String maxDate,
			@RequestParam(required = false,defaultValue = "")String account,
			@RequestParam(required = false,defaultValue = "")String mobileNo,
			@RequestParam(required = false,defaultValue = "")String namecn) {
		Date startDate = new Date();
		logger.info("queryList begin: " + startDate);

		/**
		 * 查询用户信息
		 */
		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("isDeleted", 0);
		reqMap.put("enabled", 1);
		
		if(StringUtils.isEmpty(sort)){
			reqMap.put("orderByClause","u.createdate desc");
		} else{
			reqMap.put("orderByClause",sort + " " + order);
		}

		if(!StringUtils.isBlank(account)){
			reqMap.put("_account", account.trim());
		}

		if(!StringUtils.isBlank(mobileNo)){
			reqMap.put("_mobileNo", mobileNo.trim());
		}

		if(!StringUtils.isBlank(namecn)){
			reqMap.put("_namecn", namecn.trim());
		}

		if(!StringUtils.isBlank(minDate) && !StringUtils.isBlank(maxDate)){
			try {
				if(DateUtil.parse(minDate).after(DateUtil.parse(maxDate))){
					reqMap.put("minDate", maxDate + DateUtil.START_DATE_HMS);
					reqMap.put("maxDate", minDate + DateUtil.END_DATE_HMS) ;
				}else{
					reqMap.put("minDate", minDate + DateUtil.START_DATE_HMS);
					reqMap.put("maxDate", maxDate + DateUtil.END_DATE_HMS);
				}
			} catch (ParseException e) {
				logger.error("queryList error: " ,e);
			}
		}	

		PageBounds pageBounds = new PageBounds(page, rows);
		List<MstUser> list = mstUserService.queryByList(reqMap, pageBounds);

		/**
		 * 查询用户角色信息
		 */
		PageBounds _pageBounds = new PageBounds();
		Map<String, Object> decMap = new HashMap<String, Object>();
		decMap.put("isDeleted", 0);
		decMap.put("enabled", 1);

		for(MstUser mstUser : list){
			decMap.put("userId",mstUser.getId());

			//用户附加角色信息
			List<UserRole> urs = userRoleService.queryByList(decMap, _pageBounds);
			mstUser.setUrs(urs);
		}

		PageList<MstUser> pageList = (PageList<MstUser>) list;
		Paginator paginator = pageList.getPaginator();

		HashMap<String, Object> indexPages = new HashMap<String, Object>();
		//indexPages.put("paginator", paginator);
		//indexPages.put("totalRows", paginator.getTotalCount());
		//indexPages.put("pageSize", paginator.getLimit());
		//indexPages.put("pageNumber", paginator.getPage());
		indexPages.put("total", paginator.getTotalCount());
		indexPages.put("rows", list);

		logger.info("queryList end run(s): " + DateUtil.calLastedTime(startDate));

		return indexPages;
	}

	/**
	 * 
	 * @Title: info
	 * @Description:获取用户详情信息
	 * @param @param id
	 * @param @param index_exp
	 * @param @param index_che
	 * @param @return    设定文件
	 * @return ModelAndView    返回类型
	 */
	@RequestMapping(value = "/info")
	public ModelAndView info(
			@RequestParam(required = true)String id,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che) {
		Date startDate = new Date();
		logger.info("info begin: " + startDate);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_SYSTEM + "user_info");

		//获取用户信息
		MstUser mstUser = mstUserService.selectByPrimaryKey(Integer.parseInt(id));

		
		mstUser.setRolnames("暂无角色");
		mv.addObject("mstUser", mstUser);

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("info end run(s): " + DateUtil.calLastedTime(startDate)) ;

		return mv;
	}

	/**
	 * 
	 * @Title: edit
	 * @Description: 编辑系统用户信息
	 * @param @param id
	 * @param @return    设定文件
	 * @return ModelAndView    返回类型
	 */
	@RequestMapping(value = "/edit")
	public ModelAndView edit(
			@RequestParam(required = false,defaultValue = "")String id,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che) {
		Date startDate = new Date();
		logger.info("edit begin: " + startDate);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_SYSTEM + "user_edit");

		if (!StringUtils.isBlank(id)) {
			//获取用户信息
			MstUser mstUser = mstUserService.selectByPrimaryKey(Integer.parseInt(id));
		
			mv.addObject("mstUser", mstUser);
		}

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("edit end run(s): " + DateUtil.calLastedTime(startDate)) ;

		return mv;
	}

	/**
	 * 
	 * @Title: save
	 * @Description:保存
	 * @param @param mstUser   系统用户实体
	 * @param @param br        属性校验响应对象 
	 * @param @param folPara   附带参数
	 * @param @param imagename 图片名
	 * @param @param rolids    角色ID集
	 * @param @param request   请求对象
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return String    返回类型
	 */
	@RequestMapping(value = "/save",method = RequestMethod.POST)
	public String save(
			@Valid MstUser mstUser,BindingResult br,
			FolPara folPara, String [] imagename,Integer [] rolids,
			HttpServletRequest request) throws MyException {
		Date startDate = new Date();
		logger.info("save begin: " + startDate);

		MstUser sysUser = this.getMySession().getMstUser();

		//执行业务层代码
		try {
			//拦截非法请求参数
			if (br.hasErrors()){
				List<ObjectError> ers = br.getAllErrors();
				logger.info("--------------form parameter error start-----------------------");

				for(ObjectError er : ers){
					logger.info("save faile with parameter illegal: " + er.getDefaultMessage() );
				}

				logger.info("--------------form parameter error end-----------------------");
			} else {
				if(mstUser.getId() == null){
					mstUser.setCreatedate(startDate);
					mstUser.setCreateuser(sysUser.getId());
					mstUser.setEnabled(true);
					mstUser.setIsdeleted(false);

				} else {
					mstUser.setUpdatedate(startDate);
					mstUser.setUpdateuser(sysUser.getId());
				}

				mstUserService.saveInfo(mstUser, sysUser.getId(), rolids);

				//图片资源信息维护
				if(imagename != null && imagename.length != 0){
					Map<String, String> resMap = new HashMap<String,String>();
					resMap.put("userId", sysUser.getId().toString());
					resMap.put("ownerId", mstUser.getId().toString());
					resMap.put("tableName", "MST_USER");

					Map<String, Object> dataMap = CommonUtils.getResourcesData(request, imagename, resMap,CommonEnum.SYSCODE_REOURCES_TYPE_IMAGE,false);
					
					@SuppressWarnings("unchecked")
					List<Resources> resources = (List<Resources>) dataMap.get("resources");
					
					resourcesService.saveList(resources);

					String imagePath = "";
					for(Resources resource : resources){
						imagePath += resource.getRespath() + resource.getResname() + ";";
					}

					MstUser imgUser = new MstUser();
					imgUser.setUpdatedate(startDate);
					imgUser.setUpdateuser(sysUser.getId());
					imgUser.setId(mstUser.getId());
					imgUser.setPortrait(imagePath);

					mstUserService.updateByPrimaryKeySelective(imgUser);
				}
			}

		} catch (Exception e) {
			logger.error("save error: " , e);
		}

		StringBuffer sb = new StringBuffer("?");
		sb.append("menuId=" + folPara.getMenuId());
		sb.append("&page=" + folPara.getPage());
		sb.append("&rows=" + folPara.getRows());
		sb.append("&minDate=" + folPara.getMinDate());
		sb.append("&maxDate=" + folPara.getMaxDate());
		sb.append("&usrAccount=" + folPara.getUsrAccount());
		sb.append("&mobileNo=" + folPara.getMobileNo());
		sb.append("&nameCn=" + folPara.getNameCn());
		
		sb.append("&index_exp=" + folPara.getIndex_exp());
		sb.append("&index_che=" + folPara.getIndex_che());

		logger.info("save end run(s): " + DateUtil.calLastedTime(startDate));

		return "redirect:list" + sb.toString();
	}


	/**
	 * 
	 * @Title: index
	 * @Description:index页面
	 * @param @return    设定文件
	 * @return ModelAndView    返回类型
	 */
	@RequestMapping(value = "/index")
	public ModelAndView index(
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che){
		Date startDate = new Date();
		logger.info("index begin: " + startDate);

		ModelAndView mv = new ModelAndView("/index");

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("index end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: system
	 * @Description:系统信息页面
	 * @param @return    设定文件
	 * @return ModelAndView    返回类型
	 */
	@RequestMapping(value = "/system")
	public ModelAndView system(
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che){
		Date startDate = new Date();
		logger.info("system begin: " + startDate);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_SYSTEM + "/sys_info");

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("system end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: delList
	 * @Description: 批量删除功能
	 * @param @param ids
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return boolean    返回类型
	 */
	@RequestMapping("delList")
	@ResponseBody
	public boolean delList(
			@RequestParam(required = true) String  ids ) throws MyException{
		Date startDate = new Date();
		logger.info("delList begin: "  + startDate);

		boolean flag = false;

		MstUser mstUser = this.getMySession().getMstUser();

		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("updateUser", mstUser.getId());
		reqMap.put("ids", ids);

		try {
			mstUserService.delList(reqMap);
			flag  = true;
		} catch (Exception e) {
			logger.error("delList error: " ,e);
		}

		logger.info("delList end run(s): "  + 	
				DateUtil.calLastedTime(startDate));

		return flag;
	}

	/**
	 * 
	 * @Title: doLogin
	 * @Description:登录
	 * @param @param account
	 * @param @param password
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return boolean    返回类型
	 */
	@RequestMapping(value = "/doLogin" ,method = RequestMethod.POST)
	@ResponseBody
	public boolean doLogin(
			@RequestParam(required = true) String account,
			@RequestParam(required = true) String password)throws MyException{
		Date startDate = new Date();
		logger.info("doLogin begin: " + startDate);

		boolean flag = false;

		PageBounds pageBounds = new PageBounds();

		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("enabled", 1);
		reqMap.put("isDeleted", 0);
		reqMap.put("account", account);
		reqMap.put("password", password);

		List<MstUser> users = mstUserService.queryByList(reqMap, pageBounds);

		if(users != null && users.size() != 0){
			MstUser mstUser = users.get(0);

			Map<String, Object> decMap = new HashMap<String, Object>();
			decMap.put("isDeleted", 0);
			decMap.put("enabled", 1);
			decMap.put("userId", mstUser.getId());

			//查询用户角色
			List<UserRole> urs = userRoleService.queryByList(decMap, pageBounds);
			mstUser.setUrs(urs);

			MySession mySession = new MySession();
			//存取用户信息
			mySession.setMstUser(mstUser);

			this.setMySession(mySession);

			flag = true;
		}

		logger.info("doLogin end run(s): " + DateUtil.calLastedTime(startDate));

		return flag;
	}

	/**
	 * 
	 * @Title: logout
	 * @Description: logout
	 * @param @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	@RequestMapping("/logout")
	public String logout() {
		Date startDate = new Date();
		logger.info("logout begin: " + startDate);

		this.clearSession();

		logger.info("logout end run(s): " + DateUtil.calLastedTime(startDate)); 

		return "/login";
	}
}
